"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const config_1 = require("./config");
const chalk_1 = __importDefault(require("chalk"));
const build_1 = require("./build");
const server_1 = require("./server");
const argv = require('minimist')(process.argv.slice(2), {
    string: ['port'],
    default: {
        port: 3000
    }
});
const command = argv._[0];
// init default config
const config = config_1.defaultConfig();
(() => __awaiter(void 0, void 0, void 0, function* () {
    if (!command) {
        logHelp();
        process.exit(1);
    }
    try {
        const userConfig = yield config_1.readConfig();
        Object.assign(config, userConfig);
    }
    catch (e) {
        /* handle error */
        console.debug(chalk_1.default.cyan(e));
    }
    if (command === 'serve') {
        runServer(config);
    }
    else if (command === 'build') {
        runBuild(config);
    }
    else {
        logHelp();
        process.exit(1);
    }
}))();
// run server
function runServer(options) {
    const server = server_1.createServer(options);
    // on bottom for listen
    server.listen(options.port, function (err, address) {
        if (err) {
            console.error(err);
            process.exit(1);
        }
        console.info(`tserve is listening on ${address}`);
    });
}
// use rollup to build page
function runBuild(options) {
    build_1.build(options);
}
function logHelp() {
    console.log(chalk_1.default.cyan(`
Use:
	tserve serve 
or
	tserve build

options
--port	The port of devServer (only for tserve serve)
						`));
}
